package com.lau.utils;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import java.util.concurrent.CompletableFuture;

/**
 * @author:Lau
 * @create: 2024-03-22 17:15
 * @Description: 异步调用方法工具类
 */

@Component
@Slf4j
public class AsyncMethodInvokerUtils {


    @Autowired
    private ApplicationContext context;

    @Async
    public CompletableFuture<Object> invokeAsync(Class objectClass, String methodName, Object... args) {
        Object bean = context.getBean(objectClass);
        if (bean != null) {
            try {
                Object result = null;
                if(args!=null){
                    Class<?>[] parameterTypes = new Class[args.length];
                    for (int i = 0; i < args.length; i++) {
                        parameterTypes[i] = args[i].getClass();
                    }
                    result = bean.getClass().getMethod(methodName,parameterTypes).invoke(bean,args);
                }else{
                    result = bean.getClass().getMethod(methodName).invoke(bean);
                }
                return CompletableFuture.completedFuture(result);
            } catch (Exception e) {
                log.error("异步调用{}类的{}方法ERROR：{}", objectClass.getName(), methodName, e.getMessage());
            }
        }
        return null;
    }
}
